<?php
declare (strict_types = 1);

namespace app\admin\controller;
use think\Request;
use think\exception\ValidateException;
use util\Auth as JTauth;
use app\admin\validate\CheckLogin;
class Login
{

    public function index(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->only(['username', 'password']);
            try {
                validate(CheckLogin::class)->check($data);
                $ip = $request->ip();
                $map[]=['username','=',$data['username']];
                $admin=\app\admin\model\Admin::where('username',$data['username'])->find();
                if($admin){
                    if ($admin->password != md5($data['password'] . $admin->salt)) {
                        return json(['code'=>0,'msg'=>'密码错误']);
                    }
                    if($admin->status!=1){
                        return json(['code'=>0,'msg'=>'账号禁用']);
                    }
                    $result['token'] = JTauth::getToken(['adminId' => $admin->id,'local'=>$ip]);
                    $admin->last_ip=$ip;
                    $admin->save();
                    return json(['code'=>1,'msg'=>'登录成功','data'=>$result]);
                }else{
                    return json(['code'=>0,'msg'=>'登录失败']);
                }
            } catch (ValidateException $e) {
                return json(['code'=>0,'msg'=>$e->getError()]);
            }
        }
    }

}
